package com.ericssonlabs;

import com.google.zxing.WriterException;
import com.zxing.activity.CaptureActivity;
import com.zxing.encoding.EncodingHandler;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
//yuxitao
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.Handler;
import android.os.Message;

public class BarCodeTestActivity extends Activity {
	/** Called when the activity is first created. */
	private TextView resultTextView = (TextView) this
			.findViewById(R.id.tv_scan_result);;
	private EditText qrStrEditText;
	private ImageView qrImgImageView;
	// yuxitao
	public static final int SHOW_RESPONSE = 0;
	// 新建Handler的对象，在这里接收Message，然后更新TextView控件的内容
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case SHOW_RESPONSE:
				String response = (String) msg.obj;
				// resultTextView = (TextView)
				// this.findViewById(R.id.tv_scan_result);
				resultTextView.setText(response);
				break;

			default:
				break;
			}// end of switch
		}// end of method
	};//end of Handler()

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		resultTextView = (TextView) this.findViewById(R.id.tv_scan_result);
		qrStrEditText = (EditText) this.findViewById(R.id.et_qr_string);
		qrImgImageView = (ImageView) this.findViewById(R.id.iv_qr_image);
		// //////1.scanBarCodeButton
		Button scanBarCodeButton = (Button) this
				.findViewById(R.id.btn_scan_barcode);
		scanBarCodeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 打开扫描界面扫描条形码或二维码
				Intent openCameraIntent = new Intent(BarCodeTestActivity.this,
						CaptureActivity.class);
				startActivityForResult(openCameraIntent, 0);
			}
		});
		// //////2.generateQRCodeButton
		Button generateQRCodeButton = (Button) this
				.findViewById(R.id.btn_add_qrcode);
		generateQRCodeButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					String contentString = qrStrEditText.getText().toString();
					if (!contentString.equals("")) {
						// 根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（350*350）
						Bitmap qrCodeBitmap = EncodingHandler.createQRCode(
								contentString, 350);
						qrImgImageView.setImageBitmap(qrCodeBitmap);
					} else {
						Toast.makeText(BarCodeTestActivity.this, "请先输入文本",
								Toast.LENGTH_SHORT).show();
					}

				} catch (WriterException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

		// ////////3.
		Button button_test = (Button) findViewById(R.id.button3);

		button_test.setOnClickListener(new OnClickListener() {

			// 点击按钮时，执行sendRequestWithHttpClient()方法里面的线程
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendRequestWithHttpClient();
			}
		});

	}// end of onCreate()

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 处理扫描结果（在界面上显示）
		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			String scanResult = bundle.getString("result");
			resultTextView.setText(scanResult);
		}
	}// end of method

	// 方法：发送网络请求，获取百度首页的数据。在里面开启线程
	private void sendRequestWithHttpClient() {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// 用HttpClient发送请求，分为五步
				// 第一步：创建HttpClient对象
				HttpClient httpCient = new DefaultHttpClient();
				// 第二步：创建代表请求的对象,参数是访问的服务器地址
				// HttpGet httpGet = new HttpGet("http://www.baidu.com");
				// https://gturnquist-quoters.cfapps.io/api/random
				HttpGet httpGet = new HttpGet(
						"https://gturnquist-quoters.cfapps.io/api/random");

				try {
					// 第三步：执行请求，获取服务器发还的相应对象
					HttpResponse httpResponse = httpCient.execute(httpGet);
					// 第四步：检查相应的状态是否正常：检查状态码的值是200表示正常
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						// 第五步：从相应对象当中取出数据，放到entity当中
						HttpEntity entity = httpResponse.getEntity();
						String response = EntityUtils.toString(entity, "utf-8");// 将entity当中的数据转换为字符串

						// 在子线程中将Message对象发出去
						Message message = new Message();
						message.what = SHOW_RESPONSE;
						message.obj = response.toString();
						handler.sendMessage(message);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();// 这个start()方法不要忘记了

	}

}// end of class